<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.7.2/css/all.min.css" integrity="sha256-dABdfBfUoC8vJUBOwGVdm8L9qlMWaHTIfXt+7GnZCIo=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"blog.csgrandeur.cn","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.22.0","exturl":false,"sidebar":{"position":"left","width_expanded":320,"width_dual_column":240,"display":"post","padding":18,"offset":12},"hljswrap":true,"copycode":{"enable":true,"style":"default"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"duration":200,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"top_n_per_article":1,"unescape":false,"preload":false,"trigger":"auto"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="数组与循环结构 本章介绍数组与循环结构。内存存储运行数据，数组管理同类型数据集合，占用连续内存空间。定义数组通过指定类型和大小，支持多维数组。循环包括for、while、do...while，用于重复执行代码块，支持嵌套及控制语句break和continue。实例展示如何应用这些概念解决编程问题，如分糖果游戏和质数口袋问题，强调基础知识的重要性。核心技能涵盖变量作用域、内存管理和逻辑控制。">
<meta property="og:type" content="article">
<meta property="og:title" content="03.数组与循环结构">
<meta property="og:url" content="http://blog.csgrandeur.cn/2025-03-06-03-%E6%95%B0%E7%BB%84%E4%B8%8E%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84/index.html">
<meta property="og:site_name" content="CSGrandeur&#39;s Thinking">
<meta property="og:description" content="数组与循环结构 本章介绍数组与循环结构。内存存储运行数据，数组管理同类型数据集合，占用连续内存空间。定义数组通过指定类型和大小，支持多维数组。循环包括for、while、do...while，用于重复执行代码块，支持嵌套及控制语句break和continue。实例展示如何应用这些概念解决编程问题，如分糖果游戏和质数口袋问题，强调基础知识的重要性。核心技能涵盖变量作用域、内存管理和逻辑控制。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://blog.csgrandeur.cn/2025-03-06-03-%E6%95%B0%E7%BB%84%E4%B8%8E%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84/array.jpg">
<meta property="article:published_time" content="2025-03-06T02:39:55.000Z">
<meta property="article:modified_time" content="2025-03-06T10:30:15.520Z">
<meta property="article:author" content="CSGrandeur">
<meta property="article:tag" content="ACM">
<meta property="article:tag" content="Algorithm">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://blog.csgrandeur.cn/2025-03-06-03-%E6%95%B0%E7%BB%84%E4%B8%8E%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84/array.jpg">


<link rel="canonical" href="http://blog.csgrandeur.cn/2025-03-06-03-%E6%95%B0%E7%BB%84%E4%B8%8E%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84/">


<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://blog.csgrandeur.cn/2025-03-06-03-%E6%95%B0%E7%BB%84%E4%B8%8E%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84/","path":"2025-03-06-03-数组与循环结构/","title":"03.数组与循环结构"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>03.数组与循环结构 | CSGrandeur's Thinking</title>
  

  <script src="/js/third-party/analytics/baidu-analytics.js"></script>
  <script async src="https://hm.baidu.com/hm.js?7958adf931092425a489778560129144"></script>







  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">CSGrandeur's Thinking</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">Cogito Ergo Sum</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
      <div class="search-header">
        <span class="search-icon">
          <i class="fa fa-search"></i>
        </span>
        <div class="search-input-container">
          <input autocomplete="off" autocapitalize="off" maxlength="80"
                placeholder="搜索..." spellcheck="false"
                type="search" class="search-input">
        </div>
        <span class="popup-btn-close" role="button">
          <i class="fa fa-times-circle"></i>
        </span>
      </div>
      <div class="search-result-container">
        <div class="search-result-icon">
          <i class="fa fa-spinner fa-pulse fa-5x"></i>
        </div>
      </div>
    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%95%B0%E7%BB%84%E4%B8%8E%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84"><span class="nav-number">1.</span> <span class="nav-text">数组与循环结构</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%86%85%E5%AD%98"><span class="nav-number">1.1.</span> <span class="nav-text">内存</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%95%B0%E7%BB%84"><span class="nav-number">1.2.</span> <span class="nav-text">数组</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BE%AA%E7%8E%AF"><span class="nav-number">1.3.</span> <span class="nav-text">循环</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#for%E5%BE%AA%E7%8E%AF"><span class="nav-number">1.3.1.</span> <span class="nav-text">for循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#while%E5%BE%AA%E7%8E%AF"><span class="nav-number">1.3.2.</span> <span class="nav-text">while循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#do...while%E5%BE%AA%E7%8E%AF"><span class="nav-number">1.3.3.</span> <span class="nav-text">do...while循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BE%AA%E7%8E%AF%E5%8F%AF%E4%BB%A5%E5%B5%8C%E5%A5%97"><span class="nav-number">1.3.4.</span> <span class="nav-text">循环可以嵌套</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BE%AA%E7%8E%AF%E7%9A%84%E6%8F%90%E5%89%8D%E7%BB%93%E6%9D%9F"><span class="nav-number">1.3.5.</span> <span class="nav-text">循环的提前结束</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BE%AA%E7%8E%AF%E7%9A%84%E8%B7%B3%E8%BF%87"><span class="nav-number">1.3.6.</span> <span class="nav-text">循环的跳过</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BE%8B%E9%A2%98"><span class="nav-number">1.4.</span> <span class="nav-text">例题</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E5%88%86%E7%B3%96%E6%9E%9C"><span class="nav-number">1.4.1.</span> <span class="nav-text">例：分糖果</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BE%8B%E8%B4%A8%E6%95%B0%E5%8F%A3%E8%A2%8B"><span class="nav-number">1.4.2.</span> <span class="nav-text">例：质数口袋</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">CSGrandeur</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">72</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.csgrandeur.cn/2025-03-06-03-%E6%95%B0%E7%BB%84%E4%B8%8E%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="CSGrandeur">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="03.数组与循环结构 | CSGrandeur's Thinking">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          03.数组与循环结构
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2025-03-06 10:39:55 / 修改时间：18:30:15" itemprop="dateCreated datePublished" datetime="2025-03-06T10:39:55+08:00">2025-03-06</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/" itemprop="url" rel="index"><span itemprop="name">ACM</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/ACM/ACMCOURSE/" itemprop="url" rel="index"><span itemprop="name">ACMCOURSE</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><h1 id="数组与循环结构">数组与循环结构</h1>
<p>本章介绍数组与循环结构。内存存储运行数据，数组管理同类型数据集合，占用连续内存空间。定义数组通过指定类型和大小，支持多维数组。循环包括<code>for</code>、<code>while</code>、<code>do...while</code>，用于重复执行代码块，支持嵌套及控制语句<code>break</code>和<code>continue</code>。实例展示如何应用这些概念解决编程问题，如分糖果游戏和质数口袋问题，强调基础知识的重要性。核心技能涵盖变量作用域、内存管理和逻辑控制。</p>
<span id="more"></span>
<h2 id="内存">内存</h2>
<p>内存就像计算机的"临时便签纸"，程序运行时把当前要用的数据和指令快速写在这张纸上（高速存取），关机时便签内容会被全部撕掉（断电清空），而硬盘才是长期存档的"笔记本"。</p>
<p>开一个变量<code>int a;</code>，会占据<code>32</code>个<code>bit</code>（<code>bit</code>是0101....这样的一个二进制位的单元）的内存，内存通常是以8个bit位单位处理的，所以8个比特称为“字节”，<code>int</code>就占据<code>4</code>个字节。</p>
<h2 id="数组">数组</h2>
<p>管理一连串<strong>相同类型</strong>的数据的结构，占据内存连续的一段地址。</p>
<ul>
<li>定义数组：<code>类型 数组名[数组大小]</code></li>
<li>赋值：<code>数组名[在内存中偏移开始地址的偏移量] = 要赋的值</code></li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> a[<span class="number">11</span>];</span><br><span class="line"><span class="type">double</span> b[<span class="number">11</span>];</span><br><span class="line">a[<span class="number">5</span>] = <span class="number">3</span>;</span><br><span class="line">b[<span class="number">0</span>] = <span class="number">0.5</span>;</span><br></pre></td></tr></table></figure>
<p><code>a[10]</code>在内存里开辟了连续的 <code>10</code>
个int大小的存储空间，取值和赋值能用的偏移量是<code>0~9</code>，</p>
<img src="/2025-03-06-03-%E6%95%B0%E7%BB%84%E4%B8%8E%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84/array.jpg" class="" title="数组">
<p>数组可以多个维度，从而表示“几行几列”这样的概念，甚至更高维度，“几页几行几列”/“几层几行几列”等。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> a[<span class="number">6</span>][<span class="number">6</span>][<span class="number">6</span>];</span><br><span class="line"><span class="type">char</span> c[<span class="number">11</span>][<span class="number">11</span>];</span><br></pre></td></tr></table></figure>
<p>在这个例子中，<code>c[0]</code>
表示偏移为<code>0</code>（也就是第<code>1</code>个）的一个长度为<code>11</code>的数组，把长度为<code>11</code>的数组当作单位数组的话，<code>c[1]</code>对准了偏移了1个数组的内存地址，或者说偏移了<code>11</code>个<code>char</code>的地址，<code>c[2]</code>就是偏移了2个数组，或者说偏移了<code>22</code>个<code>char</code>的地址……</p>
<h2 id="循环">循环</h2>
<p>循环就像工厂的流水线传送带，让相同的处理流程反复执行。当需要处理大量同类数据（比如数组元素）时，循环能避免写重复代码，通过"模式复用"实现高效操作。</p>
<h3 id="for循环">for循环</h3>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(初始化; 继续进行的条件; 更新操作) &#123;</span><br><span class="line">    循环的内容</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>执行顺序是：
初始化-&gt;循环的内容-&gt;更新操作-&gt;继续进行的条件（true）-&gt;循环的内容-&gt;更新操作-&gt;继续进行的条件（true）-&gt;循环的内容……</p>
<p>直到某一步“继续进行的条件”是false，则循环结束。</p>
<p>例如为数组<code>int a[10]</code>的<code>0~9</code>位置顺次输入数据</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i ++) &#123;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;a[i]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="while循环">while循环</h3>
<p>先判断是否继续，再执行，如果一开始继续进行的条件就是<code>false</code>，则循环的内容完全不会被执行</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span>(继续进行的条件) &#123;</span><br><span class="line">    循环的内容</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="do...while循环">do...while循环</h3>
<p>先执行，再判断是否继续，与 while
循环的主要区别是循环的内容至少一开始就会执行一次</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">do</span> &#123;</span><br><span class="line">    循环的内容</span><br><span class="line">&#125; <span class="keyword">while</span>(继续进行的条件);</span><br></pre></td></tr></table></figure>
<h3 id="循环可以嵌套">循环可以嵌套</h3>
<p>“循环的内容”可以是任何常规代码，循环套循环可以处理二维数组</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">11</span>; i ++) &#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> j = <span class="number">0</span>; j &lt; <span class="number">11</span>; j ++) &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%c &quot;</span>, c[i][j]);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="循环的提前结束">循环的提前结束</h3>
<p>有时候需要在达到特定目的时让循环“戛然而止”，而不是等到下一次“继续进行的条件”，用<code>break</code>，执行
<code>break</code> 时，循环整个结束，会继续循环之后的代码。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> x = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">11</span>; i ++) &#123;</span><br><span class="line">    x += <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">if</span>(x &gt; <span class="number">15</span>) &#123;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    x *= <span class="number">3</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="循环的跳过">循环的跳过</h3>
<p>有时候在循环的重复操作中，想跳过部分特殊情况，用<code>continue</code>，遇到<code>continue</code>时，<code>for</code>循环直接跳到下一次“更新操作”，<code>while</code>循环直接跳到下一次“继续进行的条件”。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> x = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">11</span>; i ++) &#123;</span><br><span class="line">    <span class="keyword">if</span>(i % <span class="number">2</span> == <span class="number">0</span>) &#123;    <span class="comment">// % 是取模，对 2 取模余数为 0，即 i 是偶数的时候</span></span><br><span class="line">        <span class="keyword">continue</span>;   <span class="comment">// 遇到continue，跳到循环体中的“i++”位置</span></span><br><span class="line">    &#125;</span><br><span class="line">    x += <span class="number">2</span>;         <span class="comment">// 如果刚刚执行了continue，则这里 x += 2 被跳过不会执行</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="例题">例题</h2>
<h3 id="例分糖果">例：分糖果</h3>
<p>有 5 位小朋友编号依次为 1,2,3,4,5
他们按照自己的编号顺序围坐在一张圆桌旁。他们身上有若干糖果，现在他们玩一个分糖果游戏。从
1 号小朋友开始，将自己的糖果均分成 3
份（如果有多余的糖果，就自己立即吃掉），自己留一份，其余两份分给和他相邻的两个小朋友。接着
2,3,4,5
号小朋友也这样做。问一轮结束后，每个小朋友手上分别有多少糖果。</p>
<p>输入：</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">8 9 10 11 12</span><br></pre></td></tr></table></figure>
<p>输出</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">11 7 9 11 6</span><br><span class="line">6</span><br></pre></td></tr></table></figure>
<p>建议的竞赛习惯：</p>
<ol type="1">
<li>数组开在 main
函数外面作为全局变量，因为函数内能用的内存（称为栈内存）比较少</li>
<li>数组大小比需要的开多一些，减少失误读写到数组外面的情况</li>
</ol>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> a[<span class="number">11</span>];   </span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i ++) &#123;</span><br><span class="line">        <span class="comment">// 用数组的 0~4 下标代替题目的 1~5 编号</span></span><br><span class="line">        <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;a[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="type">int</span> eatnum = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i ++) &#123;</span><br><span class="line">        <span class="comment">// 会发现这样 0 号能找到正确的左边的 4，4 号也能找到正确的右边的 0</span></span><br><span class="line">        <span class="type">int</span> left = (i - <span class="number">1</span> + <span class="number">5</span>) % <span class="number">5</span>;</span><br><span class="line">        <span class="type">int</span> right = (i + <span class="number">1</span>) % <span class="number">5</span>;</span><br><span class="line">        eatnum += a[i] % <span class="number">3</span>;</span><br><span class="line">        a[i] /= <span class="number">3</span>;</span><br><span class="line">        a[left] += a[i];</span><br><span class="line">        a[right] += a[i];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i ++) &#123;</span><br><span class="line">        <span class="keyword">if</span>(i != <span class="number">0</span>) <span class="built_in">printf</span>(<span class="string">&quot; &quot;</span>);</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%d&quot;</span>, a[i]);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;\n%d\n&quot;</span>, eatnum);   <span class="comment">// 上一行没打 \n，这里补上前一个\n</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="例质数口袋">例：质数口袋</h3>
<p>小 A 有一个质数口袋，里面可以装各个质数。他从 2
开始，依次判断各个自然数是不是质数，如果是质数就会把这个数字装入口袋。</p>
<p>口袋的负载量就是口袋里的所有数字之和。</p>
<p>但是口袋的承重量有限，装的质数的和不能超过
L。请问口袋里能装下几个质数？将这些质数从小往大输出，然后输出最多能装下的质数的个数，数字之间用换行隔开。</p>
<p>输入</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">5</span><br></pre></td></tr></table></figure>
<p>输出</p>
<figure class="highlight txt"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">2</span><br><span class="line">3</span><br><span class="line">2</span><br></pre></td></tr></table></figure>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;math.h&gt;</span></span></span><br><span class="line"><span class="function"><span class="type">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="type">int</span> L, cnt = <span class="number">0</span>;</span><br><span class="line">    <span class="built_in">scanf</span>(<span class="string">&quot;%d&quot;</span>, &amp;L);</span><br><span class="line">    <span class="keyword">for</span>(<span class="type">int</span> i = <span class="number">2</span>; L &gt; <span class="number">0</span>; i ++) &#123;</span><br><span class="line">        <span class="type">int</span> j = <span class="built_in">sqrt</span>(i);  <span class="comment">// j 在 for 循环之后还要用，考虑作用域，j的定义不能放在for里面</span></span><br><span class="line">        <span class="keyword">for</span>( ; j &gt; <span class="number">1</span>; j --) &#123;</span><br><span class="line">            <span class="keyword">if</span>(i % j == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(j &gt; <span class="number">1</span>) &#123;</span><br><span class="line">            <span class="comment">// 说明 i 不是质数</span></span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 没continue，执行到了这里，说明 i 是质数</span></span><br><span class="line">        <span class="keyword">if</span>(L &lt; i) &#123;</span><br><span class="line">            <span class="keyword">break</span>;  <span class="comment">// 已经无法再装了</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(L &gt;= i) &#123;</span><br><span class="line">            L -= i;</span><br><span class="line">            cnt ++;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%d\n&quot;</span>, cnt);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>知识点：在C语言中，变量的作用域（Scope）指的是变量在程序中可以被访问的有效范围。作用域决定了变量的可见性，即在代码的哪些部分可以引用该变量。</p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/ACM/" rel="tag"># ACM</a>
              <a href="/tags/Algorithm/" rel="tag"># Algorithm</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2025-03-05-02-%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E5%85%A5%E9%97%A8/" rel="prev" title="02.程序设计入门">
                  <i class="fa fa-angle-left"></i> 02.程序设计入门
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2025-03-06-04-%E5%87%BD%E6%95%B0%E4%B8%8E%E7%BB%93%E6%9E%84%E4%BD%93/" rel="next" title="04.函数与结构体">
                  04.函数与结构体 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments utterances-container"></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">CSGrandeur</span>
  </div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://fastly.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://fastly.jsdelivr.net/npm/@next-theme/pjax@0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/sidebar.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://fastly.jsdelivr.net/npm/hexo-generator-searchdb@1.4.1/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>







  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://fastly.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


<script class="next-config" data-name="utterances" type="application/json">{"enable":true,"repo":"CSGrandeur/csgrandeur.github.io","issue_term":"pathname","theme":"github-light"}</script>
<script src="/js/third-party/comments/utterances.js"></script>

</body>
</html>
